/**
 * String 암호화를 위한 모듈
 * */

if(typeof RSAKey == 'undefined' || RSAKey == null){
	document.write('<script type="text/javascript" src="/com/rsa/jsbn.js"></script>');
	document.write('<script type="text/javascript" src="/com/rsa/rsa.js"></script>');
	document.write('<script type="text/javascript" src="/com/rsa/prng4.js"></script>');
	document.write('<script type="text/javascript" src="/com/rsa/rng.js"></script>');
}

if(typeof gfn_getSubDomain != 'function'){
	function gfn_getSubDomain(){
		var prevURI = 'http://' + document.domain.toLowerCase();
		var location = document.location.href.toLowerCase();
		var subURI = location.replace(prevURI, '');
		var strSplit = subURI.split('/');

		return strSplit[1];
	}
}

CryptUtil = {
		seperateByteLen : 50,
		seperateChar : "|",
		encrypt : function(str, keyData){
			var rsa = new RSAKey();
			
			if(keyData == undefined || keyData == null){
				keyData = CryptUtil.getCryptPublicKey();
			}
			
			rsa.setPublic(keyData.modulus, keyData.exponent);
			return rsa.encrypt(str);
		},
		setCryptPublicKey : function(keyData){
			CryptUtil.keyData = keyData;
		},
		getCryptPublicKey : function(){
			// get publicKey Info
			var jqXHR = $.ajax({
				url : "getKey.sc",
				type: "POST",
				async:false
			});
			
			if(200 != jqXHR.status){
				return null;
			}
			
			return $.parseJSON(jqXHR.responseText);
		},
		splitByByte : function(str){
			var count = 0;
			var byteArray = new Array();
			var strPack = "";
			
			for(var i = 0; i < str.length; i++) {
				if(escape(str.charAt(i)).length >= 4)
					count += 3;
				else
					if(escape(str.charAt(i)) != "%0D")
						count++;
				
				strPack += str[i];

				if((count > CryptUtil.seperateByteLen) || (i+1) ==  str.length) {
					/*if(escape(str.charAt(i)) == "%0A")
						i--;*/
					
					byteArray.push(strPack);
					strPack = "";
					count = 0;
				}
			}

			return byteArray;
		},
		encryptArray : function(str, keyData){
			var arr = CryptUtil.splitByByte(str);
			var encryptArr = new Array();
			
			for(var idx in arr){
				encryptArr.push(CryptUtil.encrypt(arr[idx], keyData));
			}
			
			return encryptArr;
		},
		encryptBySeperate : function(str, keyData){
			if(gfn_isEmpty(keyData)){
				keyData = CryptUtil.getCryptPublicKey();
			} 
			return CryptUtil.encryptArray(str, keyData).join(CryptUtil.seperateChar);
		}
}